/**
 * 医疗记录字段相关数据类型定义
 * 基于实际API响应数据结构
 */

/**
 * 字段类型枚举
 */
export enum FieldType {
  /** 文本输入 */
  TEXT = '1',
  /** 数字输入 */
  NUMBER = '2',
  /** 选择器 */
  SELECT = '3',
  /** 多选 */
  CHECKBOX = '4',
  /** 日期 */
  DATE = '5'
}

/**
 * 字段范围枚举
 */
export enum FieldScope {
  /** 通用 */
  COMMON = '1',
  /** 西医 */
  WESTERN = '2',
  /** 中医 */
  CHINESE = '3'
}

/**
 * 是否标识枚举
 */
export enum YesNoFlag {
  /** 否 */
  NO = '0',
  /** 是 */
  YES = '1'
}

/**
 * 字段树节点信息
 */
export interface FieldTreeNode {
  /** 节点ID */
  id: number;
  /** 字段ID */
  fieldId: number;
  /** 节点值 */
  value: string;
  /** 节点文本 */
  text: string;
  /** 父节点ID */
  parentId: number;
  /** 排序号 */
  sortNum: number;
  /** 子节点列表 */
  children: FieldTreeNode[];
}

/**
 * 医疗记录字段信息
 */
export interface MedicalRecordField {
  fieldImages: any;
  /** 字段ID */
  fieldId: number;
  /** 字段名称 */
  fieldName: string;
  /** 字段代码 */
  fieldCode: string;
  fieldValue?:string
  /** 字段类型 */
  fieldType: FieldType;
  /** 字段范围 */
  fieldScope: FieldScope;
  /** 是否必填 */
  isRequired: YesNoFlag;
  /** 字段样式 */
  fieldStyle: string;
  /** 是否推荐 */
  isRecom: YesNoFlag;
  /** 是否支持语音 */
  isVoice: YesNoFlag;
  /** 是否支持图片 */
  isImage: YesNoFlag;
  /** 是否支持脉搏 */
  isPulse: YesNoFlag;
  /** 是否周期性 */
  isCycle: YesNoFlag;
  /** 是否默认 */
  isDefault: YesNoFlag;
  /** 排序号 */
  sortNum: number;
  /** 树形选项列表 */
  treeList: FieldTreeNode[];
}

/**
 * 医疗记录字段数据
 */
export interface MedicalRecordFieldData {
  /** 西医字段列表 */
  westernList: MedicalRecordField[];
  /** 中医字段列表 */
  chineseList: MedicalRecordField[];
}

/**
 * API响应数据结构
 */
export interface MedicalRecordFieldApiResponse {
  /** 响应代码 */
  code: string;
  /** 响应消息 */
  msg: string;
  /** 时间戳 */
  timestamp: number;
  /** 医疗记录字段数据 */
  data: MedicalRecordFieldData;
  /** 是否成功 */
  ok: boolean;
}

/**
 * 字段查询参数
 */
export interface FieldQueryParams {
  /** 字段范围 */
  fieldScope?: FieldScope;
  /** 字段类型 */
  fieldType?: FieldType;
  /** 是否必填 */
  isRequired?: YesNoFlag;
  /** 关键词搜索 */
  keyword?: string;
}

/**
 * 扁平化字段树节点（用于搜索和筛选）
 */
export interface FlatFieldTreeNode extends FieldTreeNode {
  /** 层级路径 */
  path: string[];
  /** 层级深度 */
  level: number;
  /** 完整路径文本 */
  fullPath: string;
}

/**
 * 字段值选项
 */
export interface FieldOption {
  /** 选项值 */
  value: string;
  /** 选项文本 */
  label: string;
  /** 是否禁用 */
  disabled?: boolean;
  /** 子选项 */
  children?: FieldOption[];
}

/**
 * 获取字段类型文本
 */
export const getFieldTypeText = (type: FieldType): string => {
  const typeMap: Record<FieldType, string> = {
    [FieldType.TEXT]: '文本输入',
    [FieldType.NUMBER]: '数字输入',
    [FieldType.SELECT]: '选择器',
    [FieldType.CHECKBOX]: '多选',
    [FieldType.DATE]: '日期'
  };
  return typeMap[type] || type;
};

/**
 * 获取字段范围文本
 */
export const getFieldScopeText = (scope: FieldScope): string => {
  const scopeMap: Record<FieldScope, string> = {
    [FieldScope.COMMON]: '通用',
    [FieldScope.WESTERN]: '西医',
    [FieldScope.CHINESE]: '中医'
  };
  return scopeMap[scope] || scope;
};

/**
 * 获取是否标识文本
 */
export const getYesNoFlagText = (flag: YesNoFlag): string => {
  const flagMap: Record<YesNoFlag, string> = {
    [YesNoFlag.NO]: '否',
    [YesNoFlag.YES]: '是'
  };
  return flagMap[flag] || flag;
};

/**
 * 扁平化字段树
 * @param treeNodes 树形节点数组
 * @param parentPath 父级路径
 * @param level 层级
 * @returns 扁平化的节点数组
 */
export const flattenFieldTree = (
  treeNodes: FieldTreeNode[], 
  parentPath: string[] = [], 
  level: number = 0
): FlatFieldTreeNode[] => {
  const result: FlatFieldTreeNode[] = [];
  
  treeNodes.forEach(node => {
    const currentPath = [...parentPath, node.text];
    const flatNode: FlatFieldTreeNode = {
      ...node,
      path: currentPath,
      level,
      fullPath: currentPath.join(' > ')
    };
    
    result.push(flatNode);
    
    // 递归处理子节点
    if (node.children && node.children.length > 0) {
      result.push(...flattenFieldTree(node.children, currentPath, level + 1));
    }
  });
  
  return result;
};

/**
 * 根据字段ID查找字段
 * @param fields 字段数组
 * @param fieldId 字段ID
 * @returns 找到的字段或undefined
 */
export const findFieldById = (
  fields: MedicalRecordField[], 
  fieldId: number
): MedicalRecordField | undefined => {
  return fields.find(field => field.fieldId === fieldId);
};

/**
 * 根据字段代码查找字段
 * @param fields 字段数组
 * @param fieldCode 字段代码
 * @returns 找到的字段或undefined
 */
export const findFieldByCode = (
  fields: MedicalRecordField[], 
  fieldCode: string
): MedicalRecordField | undefined => {
  return fields.find(field => field.fieldCode === fieldCode);
};

/**
 * 搜索字段
 * @param fields 字段数组
 * @param keyword 搜索关键词
 * @returns 搜索结果
 */
export const searchFields = (
  fields: MedicalRecordField[], 
  keyword: string
): MedicalRecordField[] => {
  if (!keyword.trim()) return fields;
  
  const lowerKeyword = keyword.toLowerCase();
  
  return fields.filter(field => 
    field.fieldName.toLowerCase().includes(lowerKeyword) ||
    field.fieldCode.toLowerCase().includes(lowerKeyword)
  );
};

/**
 * 根据范围筛选字段
 * @param fields 字段数组
 * @param scope 字段范围
 * @returns 筛选后的字段数组
 */
export const filterFieldsByScope = (
  fields: MedicalRecordField[], 
  scope: FieldScope
): MedicalRecordField[] => {
  return fields.filter(field => field.fieldScope === scope);
};

/**
 * 根据类型筛选字段
 * @param fields 字段数组
 * @param type 字段类型
 * @returns 筛选后的字段数组
 */
export const filterFieldsByType = (
  fields: MedicalRecordField[], 
  type: FieldType
): MedicalRecordField[] => {
  return fields.filter(field => field.fieldType === type);
};

/**
 * 获取必填字段
 * @param fields 字段数组
 * @returns 必填字段数组
 */
export const getRequiredFields = (fields: MedicalRecordField[]): MedicalRecordField[] => {
  return fields.filter(field => field.isRequired === YesNoFlag.YES);
};

/**
 * 获取推荐字段
 * @param fields 字段数组
 * @returns 推荐字段数组
 */
export const getRecommendedFields = (fields: MedicalRecordField[]): MedicalRecordField[] => {
  return fields.filter(field => field.isRecom === YesNoFlag.YES);
};

/**
 * 将字段树转换为选项格式
 * @param treeNodes 树形节点数组
 * @returns 选项数组
 */
export const convertTreeToOptions = (treeNodes: FieldTreeNode[]): FieldOption[] => {
  return treeNodes.map(node => ({
    value: node.value,
    label: node.text,
    children: node.children && node.children.length > 0 
      ? convertTreeToOptions(node.children) 
      : undefined
  }));
};

/**
 * 在树中查找节点
 * @param treeNodes 树形节点数组
 * @param value 节点值
 * @returns 找到的节点或undefined
 */
export const findTreeNodeByValue = (
  treeNodes: FieldTreeNode[], 
  value: string
): FieldTreeNode | undefined => {
  for (const node of treeNodes) {
    if (node.value === value) {
      return node;
    }
    
    if (node.children && node.children.length > 0) {
      const found = findTreeNodeByValue(node.children, value);
      if (found) return found;
    }
  }
  
  return undefined;
};

/**
 * 获取字段统计信息
 * @param data 医疗记录字段数据
 * @returns 统计信息
 */
export const getFieldStats = (data: MedicalRecordFieldData) => {
  const westernStats = {
    total: data.westernList.length,
    required: getRequiredFields(data.westernList).length,
    recommended: getRecommendedFields(data.westernList).length,
    voice: data.westernList.filter(f => f.isVoice === YesNoFlag.YES).length,
    image: data.westernList.filter(f => f.isImage === YesNoFlag.YES).length,
    pulse: data.westernList.filter(f => f.isPulse === YesNoFlag.YES).length
  };
  
  const chineseStats = {
    total: data.chineseList.length,
    required: getRequiredFields(data.chineseList).length,
    recommended: getRecommendedFields(data.chineseList).length,
    voice: data.chineseList.filter(f => f.isVoice === YesNoFlag.YES).length,
    image: data.chineseList.filter(f => f.isImage === YesNoFlag.YES).length,
    pulse: data.chineseList.filter(f => f.isPulse === YesNoFlag.YES).length
  };
  
  return {
    western: westernStats,
    chinese: chineseStats,
    total: {
      fields: westernStats.total + chineseStats.total,
      required: westernStats.required + chineseStats.required,
      recommended: westernStats.recommended + chineseStats.recommended
    }
  };
};
